package org.dsapr.codegen.processor;

import com.google.auto.service.AutoService;
import org.dsapr.codegen.common.CodeGenerateProcessor;
import org.dsapr.codegen.context.ProcessingEnvironmentHolder;
import org.dsapr.codegen.registry.ProcessorRegistry;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.ElementFilter;
import javax.tools.Diagnostic.Kind;
import java.util.Set;

@AutoService(Processor.class)
public class MyCodeGenerateProcessor extends AbstractProcessor {

    /** Main Process */
    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        for (TypeElement annotation : annotations) {
            // get elements
            Set<? extends Element> typeElements = roundEnv.getElementsAnnotatedWith(annotation);
            Set<TypeElement> filteredTypeElement = ElementFilter.typesIn(typeElements);
            for (TypeElement typeElement : filteredTypeElement) {
                CodeGenerateProcessor genProcessor = ProcessorRegistry.getProcessor(annotation.getQualifiedName().toString());
                try {
                    // generate code
                    genProcessor.generateClass(typeElement, roundEnv);
                } catch (Exception e) {
                    printError("代码生成异常：" + e);
                }
            }
        }
        return false;
    }

    /** 初始化处理器 */
    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        ProcessingEnvironmentHolder.setEnvironment(processingEnv);
        ProcessorRegistry.loadProcessors();
    }

    @Override
    public Set<String> getSupportedAnnotationTypes() {
        return ProcessorRegistry.getAnnotations();
    }

    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latestSupported();
    }

    private void printError(String message) {
        ProcessingEnvironment environment = ProcessingEnvironmentHolder.getEnvironment();
        environment.getMessager().printMessage(Kind.ERROR, message);
    }

}
